﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Xml;

namespace Aandelendelen.SiteMessage
{
	public class SiteMessageCollection : Collection<SiteMessage>
	{
		//CultureInfo culture;

		internal SiteMessageCollection()
		{
			//this.culture = new CultureInfo("nl-NL", false);

			this.ReadSiteMessages();
		}

		/// <summary>
		/// Gets all message for a given userid
		/// </summary>
		/// <param name="userId">.</param>
		public SiteMessageCollection(string userId)
		{
			SiteMessageCollection all = SiteMessageCache.GetSiteMessages();

			foreach (SiteMessage message in all)
			{
				if (message.UserId == userId || message.UserId == "*")
				{
					this.Add(message);
				}
			}
		}

		/// <summary>
		/// Gets all message for a given userid that are newer than a given date
		/// </summary>
		/// <param name="userId">.</param>
		/// <param name="timeStamp">.</param>
		public SiteMessageCollection(string userId, DateTime timeStamp)
		{
			SiteMessageCollection all = SiteMessageCache.GetSiteMessages();

			foreach (SiteMessage message in all)
			{
				if ((message.UserId == userId || message.UserId == "*") && message.TimeStamp > timeStamp)
				{
					this.Add(message);
				}
			}
		}

		private void ReadSiteMessages()
		{
			string path = HttpContext.Current.Server.MapPath("/App_Data/SiteMessage.xml");

			XmlDocument doc = new XmlDocument();

			doc.Load(path);

			XmlNodeList nodes = doc.SelectNodes("/aandelendelen/messages/message");

			if (nodes != null)
			{
				foreach (XmlNode node in nodes)
				{
					StringCollection userId = null;

					XmlAttribute attr = node.Attributes["timestamp"];

					if (attr != null)
					{
						string body = null;
						string dt = node.Attributes["timestamp"].Value;

						DateTime date = DateTime.Parse(dt);//, this.culture);

						foreach (XmlNode childNode in node.ChildNodes)
						{
							switch (childNode.LocalName)
							{
								case "recipients":
									userId = this.ReadRecipients(childNode);
									break;
								case "body":
									body = childNode.InnerText;
									break;
							}
						}

						if (body == null)
							continue;

						foreach (string user in userId)
						{
							this.Add(new SiteMessage(body, user, date));
						}
					}
				}
			}
		}

		private StringCollection ReadRecipients(XmlNode node)
		{
			StringCollection userId = new StringCollection();

			foreach (XmlNode childNode in node.ChildNodes)
			{
				if (childNode.LocalName == "user")
				{
					XmlAttribute attr = childNode.Attributes["id"];
					if (attr != null)
					{
						userId.Add(attr.Value.ToLower());
					}
				}
			}

			return userId;
		}
	}
}